/**
 * 
 */
package vl.scanfile;

import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import org.springframework.web.portlet.bind.annotation.ResourceMapping;
import org.springframework.web.servlet.ModelAndView;

import vl.scanfile.json.JsonVO;
import vl.scanfile.ulti.FtpVOSerializer;
import vl.scanfile.ulti.Tree;
import vl.scanfile.ulti.TreeNode;
import vl.scanfile.vo.FtpVO;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.liferay.portal.kernel.dao.jdbc.DataAccess;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.model.User;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.sun.org.apache.bcel.internal.generic.L2D;

/**
 * @author Chau
 *
 */

@Controller
@RequestMapping("VIEW")
public class ScanFilePortlet {
	
	private final static int TEN_MB = 10485760;

	private final static String fileInputName = "fileupload";

	FTPClient client = new FTPClient();
	FileInputStream fis = null;
	String server = "54.169.135.244";
	int port = 21;
	String user = "sonhb";
	String pass = "123123";
	
	@RenderMapping
	public String handleRenderRequest(RenderRequest request,RenderResponse response,Model model){
	  
		return "defaultRender";
	}
	
	@ResourceMapping(value="test")
	public void ftpInfoSave(ResourceRequest request, ResourceResponse response) throws IOException{
		//JSONObject json = JSONFactoryUtil.createJSONObject();
        try{
/*	        ThemeDisplay themeDisplay  =(ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY);
	        User user = themeDisplay .getUser();
	        request.getParameter("data");
	        response.setCharacterEncoding("UTF-8");
	        json.put("firstName",user != null ? user.getFirstName() :"");
	        json.put("lastName",user != null ? user.getLastName() :"");*/
        	
        	String server = request.getParameter("server");
        	String username = request.getParameter("username");
        	String password = request.getParameter("password");
        	String port = request.getParameter("port");
        	java.sql.Connection con = null, con1 = null;
    		java.sql.Statement st = null, st1 = null;
    		try {
    			con1 = DataAccess.getConnection();
    			st1 = con1.createStatement();
    			String query = "DELETE FROM c_config";
    			st1.executeQuery(query);
    		} 
    		catch (Exception e) {
    		} 
    		finally {
    			st1.close();
    			con1.close();
    		}
    		try {
    			con = DataAccess.getConnection();
    			st = con.createStatement();
    			String query = "INSERT INTO c_config(pr_key, server, username, password, port) VALUES(1, '" + server + "', '" + username + "', '" + password + "', '" + port + "')";
    			st.executeQuery(query);
    		} 
    		catch (Exception e) {
    		} 
    		finally {
    			st.close();
    			con.close();
    		}
	        response.getWriter().write("Ok");
        }catch (Exception e) {
        }   
	}
	
	@ResourceMapping(value="loadTree")
	public void loadTree(ResourceRequest request, ResourceResponse response) throws IOException, SQLException{
    	java.sql.Connection con = null;
		java.sql.Statement st = null;
		Tree<FtpVO> folderTree = new Tree<FtpVO>();
		FtpVO temp = new FtpVO();
		temp.setType("root");
		temp.setText("root");
		TreeNode<FtpVO> root = new TreeNode<FtpVO>(temp);
		DatabaseSupporter.listDirectoryFromDB(con, root);
		folderTree.setRoot(root);
		Gson gson = new Gson();
        String json = gson.toJson(folderTree);
        json = json.replaceAll("\"data\":", "");
        json = json.replaceFirst("\"root\":", "");
        json = json.replaceAll("\\{\"text\"", "\"text\"");
        json = json.replaceAll("\\},\"children", ",\"children");
        json = json.substring(1, json.length() - 1);
        JSONObject jsonObject =  JSONFactoryUtil.createJSONObject();
        jsonObject.put("folder", json);
        response.getWriter().write(jsonObject.toString());
	}
	
	@ResourceMapping(value="loadFtpTree")
	public void loadFtpTree(ResourceRequest request, ResourceResponse response) throws IOException {
		Tree<FtpVO> folderTree = new Tree<FtpVO>();
		FtpVO temp = new FtpVO();
		temp.setType("root");
		temp.setText("root");
		TreeNode<FtpVO> root = new TreeNode<FtpVO>(temp);
		try {
			client.connect(server);
			client.login(user, pass);

			FtpSupporter.listDirectory(client, "/", "", 0, root);

			folderTree.setRoot(root);

			client.logout();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				client.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
        Gson gson = new Gson();
        String json = gson.toJson(folderTree);
        json = json.replaceAll("\"data\":", "");
        json = json.replaceFirst("\"root\":", "");
        json = json.replaceAll("\\{\"text\"", "\"text\"");
        json = json.replaceAll("\\},\"children", ",\"children");
        json = json.substring(1, json.length() - 1);
        JSONObject jsonObject =  JSONFactoryUtil.createJSONObject();
        jsonObject.put("folder", json);
        response.getWriter().write(jsonObject.toString());
    }
	
	@ResourceMapping(value="addKho")
	public void addKho(ResourceRequest request, ResourceResponse response) throws IOException, SQLException{
        String ten = request.getParameter("ten");
        java.sql.Connection con = null;
        int ma1 = DatabaseSupporter.createKho(con, ten);
        Gson gson = new Gson();
        FtpVO vo = new FtpVO();
        vo.setMa(ma1);
        vo.setText(ten);
        vo.setType("kho");
        String json = gson.toJson(vo);
        response.getWriter().write(json);
	}
	@ResourceMapping(value="addTu")
	public void addTu(ResourceRequest request, ResourceResponse response) throws IOException, SQLException{
        String ten = request.getParameter("ten");
        String sMa = request.getParameter("ma");
        int ma = Integer.parseInt(sMa);
        java.sql.Connection con = null;
        int ma1 = DatabaseSupporter.createTu(con, ten, ma);
        Gson gson = new Gson();
        FtpVO vo = new FtpVO();
        vo.setMa(ma1);
        vo.setText(ten);
        vo.setType("tu");
        String json = gson.toJson(vo);
        response.getWriter().write(json);
	}
	@ResourceMapping(value="addKe")
	public void addKe(ResourceRequest request, ResourceResponse response) throws IOException, SQLException{
		String ten = request.getParameter("ten");
        String sMa = request.getParameter("ma");
        int ma = Integer.parseInt(sMa);
        java.sql.Connection con = null;
        int ma1 = DatabaseSupporter.createKe(con, ten, ma);
        Gson gson = new Gson();
        FtpVO vo = new FtpVO();
        vo.setMa(ma1);
        vo.setText(ten);
        vo.setType("ke");
        String json = gson.toJson(vo);
        response.getWriter().write(json);
	}
	@ResourceMapping(value="addHop")
	public void addHop(ResourceRequest request, ResourceResponse response) throws IOException, SQLException{
		String ten = request.getParameter("ten");
        String sMa = request.getParameter("ma");
        int ma = Integer.parseInt(sMa);
        java.sql.Connection con = null;
        int ma1 = DatabaseSupporter.createHop(con, ten, ma);
        Gson gson = new Gson();
        FtpVO vo = new FtpVO();
        vo.setMa(ma1);
        vo.setText(ten);
        vo.setType("hop");
        String json = gson.toJson(vo);
        response.getWriter().write(json);
	}
	@ResourceMapping(value="addFile")
	public void addFile(ResourceRequest request, ResourceResponse response) throws IOException, SQLException{
		String ten = request.getParameter("ten");
        String sMa = request.getParameter("ma");
        String file = request.getParameter("");
        String duongDan = "";
        int ma_hoso = -1;
        int ma = Integer.parseInt(sMa);
        java.sql.Connection con = null;
        DatabaseSupporter.createHoSo(con, ma_hoso, ma, ten, duongDan);
        response.getWriter().write("Okay");
	}
	
	public void upload(ActionRequest request, ActionResponse response)
			throws Exception {
		java.sql.Connection con = null;
		java.sql.Statement st = null;
		try {
			con = DataAccess.getConnection();
			st = con.createStatement();
			java.sql.ResultSet rs = st.executeQuery("SELECT * FROM c_loaihoso");
			while (rs.next()) {
				String firstName = rs.getString("ma_hoso");
				String lastName = rs.getString("ten_hoso");
				System.out.println("ma ho so:" + firstName);
				System.out.println("ten ho so:" + lastName);
			}
		} 
		catch (Exception e) {
		} 
		finally {
			st.close();
			con.close();
		}
		UploadPortletRequest uploadRequest = PortalUtil
				.getUploadPortletRequest(request);

		long sizeInBytes = uploadRequest.getSize(fileInputName);

		if (uploadRequest.getSize(fileInputName) == 0) {
			throw new Exception("Received file is 0 bytes!");
		}

		File uploadedFile = uploadRequest.getFile(fileInputName);

		String sourceFileName = uploadRequest.getFileName(fileInputName);

		if (sizeInBytes > TEN_MB) {
			throw new Exception("Out of file size!");
		}

		try {
			client.connect(server);
			client.login(user, pass);

			fis = new FileInputStream(uploadedFile);

			client.storeFile(sourceFileName, fis);
			client.logout();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				client.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void createFolder(ActionRequest request, ActionResponse response)
			throws Exception {

		UploadPortletRequest uploadRequest = PortalUtil
				.getUploadPortletRequest(request);

		String name = uploadRequest.getParameter("folderName");


		try {
			client.connect(server);
			client.login(user, pass);

			ftpCreateDirectoryTree(client, name);
			client.logout();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				client.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static void ftpCreateDirectoryTree(FTPClient client, String dirTree)
			throws IOException {

		boolean dirExists = true;

		// tokenize the string and attempt to change into each directory level.
		// If you cannot, then start creating.
		String[] directories = dirTree.split("/");
		for (String dir : directories) {
			if (!dir.isEmpty()) {
				if (dirExists) {
					dirExists = client.changeWorkingDirectory(dir);
				}
				if (!dirExists) {
					if (!client.makeDirectory(dir)) {
						throw new IOException(
								"Unable to create remote directory '" + dir
										+ "'.  error='"
										+ client.getReplyString() + "'");
					}
					if (!client.changeWorkingDirectory(dir)) {
						throw new IOException(
								"Unable to change into newly created remote directory '"
										+ dir + "'.  error='"
										+ client.getReplyString() + "'");
					}
				}
			}
		}
	}
	
	/*@Override
	public void serveResource(ResourceRequest resourceRequest,
            ResourceResponse resourceResponse) throws IOException,
            PortletException {
		
		Tree<FtpVO> folderTree = new Tree<FtpVO>();
		FtpVO temp = new FtpVO();
		temp.setType("root");
		temp.setText("root");
		TreeNode<FtpVO> root = new TreeNode<FtpVO>(temp);
		try {
			client.connect(server);
			client.login(user, pass);

			FtpSupporter.listDirectory(client, "/", "", 0, root);

			folderTree.setRoot(root);

			client.logout();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
				client.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
        resourceResponse.setContentType("application/json");
        PrintWriter writer = resourceResponse.getWriter();
        Gson gson = new Gson();
        String json = gson.toJson(folderTree);
        json = json.replaceAll("\"data\":", "");
        json = json.replaceFirst("\"root\":", "");
        json = json.replaceAll("\\{\"text\"", "\"text\"");
        json = json.replaceAll("\\},\"children", ",\"children");
        json = json.substring(1, json.length() - 1);
        JSONObject jsonObject =  JSONFactoryUtil.createJSONObject();
        jsonObject.put("folder", json);
        writer.print(jsonObject.toString());
        writer.flush();
        writer.close();
        super.serveResource(resourceRequest, resourceResponse);
    }*/
	
	
}
